//
//  ContactList.m
//  ContactViewerIos
//
//  Created by ANDY SELVIG on 3/7/12.
//  Copyright (c) 2012 Tiny Mission. All rights reserved.
//

#import "ContactList.h"
#import "FileUtilities.h"
#import "JSONUtilities.h"

static ContactList* _singleton = nil;
NSString * const CONTACTS_KEY = @"Contacts";
NSString * const SINGLE_CONTACT_KEY = @"Contact_";
NSString * const CONTACTS_JSON_FILE = @"Contacts.json";
@implementation ContactList

@synthesize allContacts=_contacts;


-(id)initWithCapacity:(NSInteger)capacity {
    self = [super init];
    _contacts = [[NSMutableArray alloc] initWithCapacity:capacity];
    return self;
}

+(void)initSingleton {
    if (nil == _singleton)
    {
        _singleton = [[ContactList alloc] initWithCapacity:0];
        [_singleton readContactsFromFile];
    }
}

-(void)addContact:(Contact*)contact {
    [_contacts addObject:contact];
    [self writeContactsToFile];
}

-(void)updateContact:(Contact*)contact {
    [self writeContactsToFile];
}

-(void)deleteContact:(Contact*)contact {
    [_contacts removeObject: contact];
    [self writeContactsToFile];
}

-(Contact*)contactAtIndex:(NSInteger)index {
    return [_contacts objectAtIndex:index];
}

+(ContactList*)singleton {
    return _singleton;
}

-(NSInteger)count {
    return [_contacts count];
}

-(void)writeContactsToFile {
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    NSInteger contactIndex = 0;
    for (Contact* contact in _contacts) {
        [dictionary setObject: [contact toDictionary] forKey: 
            [ NSString stringWithFormat:@"%@%d",SINGLE_CONTACT_KEY, contactIndex]];
        ++contactIndex;
    }

    NSDictionary* contactDict = 
        [NSDictionary dictionaryWithObject:dictionary forKey:CONTACTS_KEY];

    NSString* jsonString = [JSONUtilities dictionaryToJSON:contactDict];
    [FileUtilities writeData:jsonString toFileInDocumentsDirectory:CONTACTS_JSON_FILE];
}

-(void)readContactsFromFile {
    NSString* jsonString = 
        [FileUtilities readDataFromFileInDocumentsDirectory:CONTACTS_JSON_FILE];
    if (nil != jsonString) {
        NSDictionary* contactDict = 
            [[JSONUtilities dictionaryFromJSON:jsonString] objectForKey:CONTACTS_KEY];
        
        [_contacts removeAllObjects];
        NSEnumerator *enumerator = [contactDict keyEnumerator];
        id key;
        while ((key = [enumerator nextObject])) {
            NSDictionary *contact = [contactDict objectForKey:key];
            [_contacts addObject: [[Contact alloc] initFromDictionary:contact]];
        }
    }
}

@end
